<template >
  <div class="post-list" v-if="PostList">
    <article v-for="post in PostList" v-bind:key="post._id" class="card mb-3 shadow-sm">
      <div class="card-body">
        <a  href="#" @click.prevent="goPostDetail(post._id)">{{post.title}}</a>
        <div class="row my-3 align-items-center">
          <div v-if="post.image" class="col-4">
            <img :src="post.image && post.image.url" :alt="post.title" class="rounded-lg">
          </div>
          <p :class="{'col-8': post.image && post.image.url}" class="text-muted">{{post.excerpt}}</p>
        </div>
        <span class="text-muted">{{post.createdAt}}</span>
      </div>
    </article>
  </div>
</template>

<script lang='ts'>
/* 使用store action异步加载 */
import {defineComponent, PropType,computed} from 'vue'
import {useStore} from 'vuex'
import {GlobalDataProps,PostProps} from '@/store/index'

import router from '@/route'
export default defineComponent({
    props: {
        list: {
            require : true,
            type: Array as PropType<PostProps[]>
        },
        currentId: {
          require: true,
          type: Number
        }
    },
    setup(props) {
      const store = useStore<GlobalDataProps>()
      const lists  = computed(() => store.state.posts.filter(c => c.column == props.currentId))

    // 更具计算属性把图片缩放
    const PostList = computed(() => {
      return props.list?.map((item)=> {
        if (item.image) {
          const {image} = item
          const ImgStr = '?x-oss-process=image/resize,m_pad,h_50,w_50,color_FF0000'
          var reg = RegExp(/x-oss-process=image/);
          const imgUrl = image.url || ''

          // image.url = image.url + ImgStr
          image.url = reg.test(imgUrl) ? imgUrl: (imgUrl+ImgStr)
        }
        return item
      })
    })
      const goPostDetail = (id:string) => {
        router.push({
          name: 'PostDetail',
          params: {
            id
          }
        })
      }
      return {
        lists,
        goPostDetail,
        PostList
      }
    }

})
</script>

<style scoped>
.card-body img {
  width: 50px;
  height: 50px;
}
</style>